package com.tjbank.cssys.framework.base.configuration;

import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.CodeSignature;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Aspect
@Order(0)
@Component
public class LogAop {

    @Pointcut("execution(* com.tansun.magicube..web.controller..*.*(..)) ")
    public void logPointCut() {
    }

    @Around(value = "logPointCut()")
    public Object logOperate(ProceedingJoinPoint joinPoint) throws Throwable {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
        String methodName = method.getDeclaringClass().getSimpleName() + "." + method.getName();

        Object[] paramValues = joinPoint.getArgs();
        String[] paramNames = ((CodeSignature) joinPoint.getSignature()).getParameterNames();
        StringBuilder params = new StringBuilder();
        for (int i = 0; i < paramNames.length; i++) {
            String name = paramValues[i].getClass().getName();
            if (!StringUtils.equals("org.springframework.validation.BeanPropertyBindingResult", name)) {
                params.append(paramNames[i] + " = " + JSON.toJSONString(paramValues[i], SerializerFeature.IgnoreNonFieldGetter));
            }
        }
        log.debug(joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
        log.debug(">>>>>>>>>>>>>>>>>>接口URL : {} ----{} 方式请求", request.getRequestURL().toString(), request.getMethod());
        log.debug(">>>>>>>>>>>>>>>>>>请求参数：{} ", params);
        log.debug(">>>>>>>>>>>>>>>>>>方法名称：{} ", methodName);
        StopWatch stopWatch = new StopWatch("==================耗时");
        stopWatch.start(methodName);

        Object result = joinPoint.proceed();
        stopWatch.stop();

        log.debug(stopWatch.prettyPrint());
        log.debug("<<<<<<<<<<<<<<<<<<出参：{}", JSON.toJSON(result));
        return result;
    }
}

//: >>>>>>>>>>>>>>>>>>接口URL : http://localhost:8088/dept/ ----GET 方式请求
//: >>>>>>>>>>>>>>>>>>请求参数："deptDTO = {};pageable = {\"sort\":{}};" 
//: >>>>>>>>>>>>>>>>>>方法名称：DeptController.queryDept
//: Creating a new SqlSession
//: SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@6eeacb4e] was not registered for synchronization because synchronization is not active
//: JDBC Connection [HikariProxyConnection@1249748796 wrapping com.mysql.jdbc.JDBC4Connection@4ef87203] will not be managed by Spring
//: ==>  Preparing: select ID, DEPT_NUM, DEPT_NAME, AUTHORITY_ID, AUTHORITY_NAME, DEPT_STATE, TENAN_ID, CREATE_USER, UPDATE_USER, CREATE_TIME, UPDATE_TIME, IS_DELETED from iam_dept WHERE IS_DELETED = ? order by UPDATE_TIME DESC limit ? 
//: ==> Parameters: false(Boolean), 20(Integer)
//: <==      Total: 4
//: Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@6eeacb4e]
//: Creating a new SqlSession
//: SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@7367abec] was not registered for synchronization because synchronization is not active
//: JDBC Connection [HikariProxyConnection@1511636671 wrapping com.mysql.jdbc.JDBC4Connection@4ef87203] will not be managed by Spring
//: ==>  Preparing: select count(*) from iam_dept WHERE IS_DELETED = ? 
//: ==> Parameters: false(Boolean)
//: <==      Total: 1
//: Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@7367abec]
//: StopWatch '==================耗时': running time (millis) = 203
//-----------------------------------------
//ms     %     Task name
//-----------------------------------------
//00203  100%  DeptController.queryDept
//
//: <<<<<<<<<<<<<<<<<<出参：{"code":200,"data":{"number":0,"last":true,"numberOfElements":4,"size":20,"totalPages":1,"pageable":{"paged":true,"pageNumber":0,"offset":0,"pageSize":20,"unpaged":false,"sort":{"unsorted":true,"sorted":false,"empty":true}},"sort":{"unsorted":true,"sorted":false,"empty":true},"content":[{"deptName":"新增角色","deptId":"f32e4065442b49e9ae58396776dcc89e","deptNum":"1cad","deptState":"生效","updateUser":"系统管理员","updateTime":1586851911000,"tenanId":"91310117MA1J196M4B","authorityId":"1cad","isDeleted":false,"createTime":1586851911000,"createUser":"系统管理员","id":"f32e4065442b49e9ae58396776dcc89e"},{"deptName":"新增角色","deptId":"d5f090647f7c4667b923cf578d427476","deptNum":"d57c","deptState":"生效","updateUser":"系统管理员","updateTime":1586850028000,"tenanId":"91310117MA1J196M4B","authorityId":"d57c","isDeleted":false,"createTime":1586850028000,"createUser":"系统管理员","id":"d5f090647f7c4667b923cf578d427476"},{"deptName":"前新增","deptId":"5bf9d5a29615464f94c2652e80bf142f","deptNum":"9910","deptState":"生效","updateUser":"系统管理员","updateTime":1586849685000,"tenanId":"91310117MA1J196M4B","authorityId":"9910","isDeleted":false,"createTime":1586849685000,"createUser":"系统管理员","id":"5bf9d5a29615464f94c2652e80bf142f"},{"deptName":"总行卡部","authorityName":"测试权限","deptId":"91310117MA1J196M4Bdepartment001","deptNum":"91310117MA1J196M4Bdepartment001","deptState":"生效","updateUser":"admin","updateTime":1584683447000,"tenanId":"91310117MA1J196M4B","authorityId":"9e9668247660472ea4564cf76857c6bb","isDeleted":false,"createTime":1584683447000,"createUser":"admin","id":"91310117MA1J196M4Bdepartment001"}],"first":true,"empty":false,"totalElements":4},"success":true}
